package com.jy.api.controller.admin;

import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.payRes.DiscountPromotionDto;
import com.jy.api.service.DiscountPromotionService;
import com.jy.api.signUpReq.promotion.DisPromotionEditParams;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "v1/admin/dp", produces = "application/json;charset=utf-8")
public class DiscountPromotionController {

    @Autowired
    private DiscountPromotionService discountPromotionService;
    @Autowired
    private DiscountPromotionDao discountPromotionDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private DiscountPromotionProductDao discountPromotionProductDao;
    @Autowired
    private DiscountPromotionOrderDao discountPromotionOrderDao;

    @Autowired
    private DiscountOrderItemDao discountOrderItemDao;

    /**
     * 获取折扣活动列表详情
     *
     * @param
     * @return
     */
    @GetMapping("/product/list")
    public ResponseEntity list(@RequestParam("promotionId") int promotionId, @RequestParam("page") int page, @RequestParam("size") int size) {
        return new ResponseEntity(discountPromotionProductDao.findAllByPromotionId(promotionId, new PageRequest(page, size, new Sort(Sort.Direction.DESC, "id"))), HttpStatus.OK);
    }

    /**
     * 获取折扣活动订单列表
     *
     * @param
     * @return
     */
    @GetMapping("/sales/list")
    public ResponseEntity salesList(@RequestParam("promotionId") int promotionId, @RequestParam(value = "begin", required = false) String begin, @RequestParam(value = "end", required = false) String end, @RequestParam("page") int page, @RequestParam("size") int size) throws Exception {
        if (!StringUtils.isBlank(begin) && !StringUtils.isBlank(end)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            return new ResponseEntity(discountOrderItemDao.findAllByPromotionIdAndPayTimeBetween(promotionId, sdf.parse(begin), sdf.parse(end), new PageRequest(page, size, new Sort(Sort.Direction.DESC, "id"))), HttpStatus.OK);
        }
        return new ResponseEntity(discountOrderItemDao.findAllByPromotionId(promotionId, new PageRequest(page, size, new Sort(Sort.Direction.DESC, "id"))), HttpStatus.OK);
    }

    /**
     * 获取折扣活动列表
     *
     * @param
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity list(@RequestParam("storeId") String storeId, @RequestParam("type") PromotionType type, @RequestParam("page") int page, @RequestParam("size") int size) throws Exception {
        return new ResponseEntity(discountPromotionService.findListByPage(storeId, type, page, size), HttpStatus.OK);
    }


    /**
     * 获取折扣活动详情
     *
     * @param
     * @return
     */
    @GetMapping("/detail")
    public ResponseEntity detail(@RequestParam("id") int id) {
        DiscountPromotion promotion = discountPromotionDao.findOne(id);
        if (promotion == null) {
            return new ResponseEntity("查看的折扣活动详情不存在，请刷新后重试", HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity(promotion, HttpStatus.OK);
    }

    /**
     * 取消折扣活动
     *
     * @param
     * @return
     */
    @GetMapping("/cancel")
    public ResponseEntity cancel(@RequestParam("id") int id) {
        DiscountPromotion promotion = discountPromotionDao.findOne(id);
        if (promotion == null) {
            return new ResponseEntity("查看的折扣活动详情不存在，请刷新后重试", HttpStatus.BAD_REQUEST);
        }
        promotion.setPromotionType(PromotionType.cancel);
        discountPromotionDao.save(promotion);
        discountPromotionProductDao.updateUnfinishedOrder(3, promotion.getId());
        return new ResponseEntity(HttpStatus.OK);
    }

    @PostMapping("/add")
    public ResponseEntity edit(@RequestBody DisPromotionEditParams params) {
        DiscountPromotion promotion = new DiscountPromotion();
        Map map = new HashMap();
        List<String> strings = new ArrayList<>();
        for (DisPromotionEditParams.DiscountProduct product : params.getProducts()) {
            strings.add(product.getProductId());
        }

        List<Object[]> objects = discountPromotionDao.countByPromotionTypeAndProducts(strings, params.getStoreId());
        for (Object[] object : objects) {
            map.put(object[1], object[0]);
        }

        List<Product> productList = productDao.findListByIdIn(strings);
        for (Product s : productList) {
            if (map.containsKey(s.getId())) {
                return new ResponseEntity(s.getName() + "已经存在于其他活动，请核实", HttpStatus.BAD_REQUEST);
            }
            if (s.isMemberShow()) {
                return new ResponseEntity(s.getName() + "已开启折扣，请前往商品资料关闭后再进行添加", HttpStatus.BAD_REQUEST);
            }
            if (s.isDisShow()) {
                return new ResponseEntity(s.getName() + "已开启折扣，请前往商品资料关闭后再进行添加", HttpStatus.BAD_REQUEST);
            }
            if (params.getDiscountType().equals(DiscountType.reduce) && s.getSalesPrice() < params.getReduceAmount() / 100) {
                return new ResponseEntity(s.getName() + "折扣后售价为负", HttpStatus.BAD_REQUEST);
            }
            if (s.isHaveMatchProductEnabled()) {
                return new ResponseEntity(s.getName() + "含有配品，不允许添加到折扣活动，请核实", HttpStatus.BAD_REQUEST);
            }
        }
        List<DiscountPromotionProduct> promotionProducts = new ArrayList<>();
        List<Product> products = new ArrayList<>();

        BeanUtils.copyProperties(params, promotion, defaultIgnoreProperties());
        promotion.setBeginTime(params.getBegin());
        promotion.setEndTime(params.getEnd());
        if (params.getTimeType().equals(TimeType.forever)) {
            promotion.setPromotionType(PromotionType.ing);
        } else {
            promotion.setPromotionType(PromotionType.no);
        }
        discountPromotionDao.save(promotion);
        for (DisPromotionEditParams.DiscountProduct product : params.getProducts()) {
            Product p = productDao.findOne(product.getProductId());

            DiscountPromotionProduct promotionProduct = new DiscountPromotionProduct();
            promotionProduct.setProductId(p.getId());
            promotionProduct.setProductName(p.getName());
            promotionProduct.setPromotionId(promotion.getId());
            if (params.getTimeType().equals(TimeType.forever)) {
                promotionProduct.setPromotionType(PromotionType.ing);
            } else {
                promotionProduct.setPromotionType(PromotionType.no);
            }
            promotionProduct.setDiscountCommission(product.getDiscountCommission());
            promotionProducts.add(promotionProduct);
            products.add(p);
        }
        productDao.save(products);

        discountPromotionProductDao.save(promotionProducts);
        return new ResponseEntity(HttpStatus.OK);
    }


    public static final String[] defaultIgnoreProperties(String... mores) {
        final String[] bases = {"id", "addTime"};
        return (String[]) ArrayUtils.addAll(bases, mores);
    }

}
